package com.cbgolf.oa.util;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.util.Base64;
import android.util.Log;
import com.cbgolf.oa.app.App;
import com.cbgolf.oa.inteface.IBmapWorker;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class BitmapUtils {

  private static int ERROR_IMAGE = -1;
  private static int LOADING_IMAGE = -1;

  private BitmapUtils() {

  }

  public static void setERROR_IMAGE(int eRROR_IMAGE) {
    ERROR_IMAGE = eRROR_IMAGE;
  }

  public static void setLOADING_IMAGE(int lOADING_IMAGE) {
    LOADING_IMAGE = lOADING_IMAGE;
  }

//    public static void loadBitmap(String urlOrPath, ImageView view) {
//        loadBitmap(urlOrPath, view, 0, 0);
//    }

//    public static void loadBitmap(String urlOrPath, ImageView view, int width, int height) {
//        loadBitmap(urlOrPath, view, width, height, null);
//    }
//
//    public static void loadBitmap(File file, ImageView view) {
//        loadBitmap(Uri.fromFile(file), view, 0, 0);
//    }
//
//    public static void loadBitmap(File file, ImageView view, int width, int height) {
//        loadBitmap(Uri.fromFile(file), view, width, height, null);
//    }
//
//    public static void loadBitmap(Uri uri, ImageView view) {
//        loadBitmap(uri, view, 0, 0);
//    }
//
//    public static void loadBitmap(Uri uri, ImageView view, int width, int height) {
//        loadBitmap(uri, view, width, height, null);
//    }

//    public static void loadBitmap(String urlOrPath, ImageView view, int width, int height,
//                                  com.squareup.picasso.Callback callback) {
//        if (Util.isNull(urlOrPath)) {
//            Log.e("loadBitmap url is null ", urlOrPath);
//            if (null != callback) {
//                callback.onError();
//            }
//            return;
//        }
//        RequestCreator rc = Picasso.with(view.getContext()).load(urlOrPath);
//        if (-1 != ERROR_IMAGE)
//            rc.error(ERROR_IMAGE);
//        if (-1 != LOADING_IMAGE)
//            rc.placeholder(LOADING_IMAGE);
//        if (0 != width && height != 0) {
//            rc.resize(width, height).centerCrop();
//        }
//        rc.into(view, callback);
//    }
//
//    public static void loadBitmap(Uri uri, ImageView view, int width, int height,
//                                  com.squareup.picasso.Callback callback) {
//        RequestCreator rc = Picasso.with(view.getContext()).load(uri);
//        if (-1 != ERROR_IMAGE)
//            rc.error(ERROR_IMAGE);
//        if (-1 != LOADING_IMAGE)
//            rc.placeholder(LOADING_IMAGE);
//        if (0 != width && height != 0) {
//            rc.resize(width, height).centerCrop();
//        }
//        rc.into(view, callback);
//    }

  public static int caculateInSampleSize(Options options, int reqWidth, int reqHeight) {
    int width = options.outWidth;
    int height = options.outHeight;
    int inSampleSize = 1;
    if (height > reqHeight || width > reqWidth) {
      // 计算出实际宽高和目标宽高的比率
      final int heightRatio = Math.round((float) height / (float) reqHeight);
      final int widthRatio = Math.round((float) width / (float) reqWidth);
      // 选择宽和高中最小的比率作为inSampleSize的值，这样可以保证最终图片的宽和高
      // 一定都会大于等于目标的宽和高。
      inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }
    return inSampleSize;
  }

  public static Bitmap fileToBitmap(File file, int width, int height) {
    Bitmap bitmap = null;
    Options options = new Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(file.getAbsolutePath(), options);
    options.inJustDecodeBounds = false;
    options.inSampleSize = caculateInSampleSize(options, width, height);
    options.inDither = false;
    options.inPreferredConfig = Config.ARGB_8888;
    bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
    return bitmap;
  }

  /**
   * 读取图片属性：旋转的角度
   *
   * @param path 图片绝对路径
   * @return degree旋转的角度
   */
  public static int readPictureDegree(String path) {
    int degree = 0;
    try {
      ExifInterface exifInterface = new ExifInterface(path);
      int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
          ExifInterface.ORIENTATION_NORMAL);
      switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_90:
          degree = 90;
          break;
        case ExifInterface.ORIENTATION_ROTATE_180:
          degree = 180;
          break;
        case ExifInterface.ORIENTATION_ROTATE_270:
          degree = 270;
          break;
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    return degree;
  }

  /**
   * 放大缩小图片
   */
  public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
    Bitmap newbmp = null;
    if (bitmap != null) {
      int width = bitmap.getWidth();
      int height = bitmap.getHeight();
      Matrix matrix = new Matrix();
      float scaleWidht = ((float) w / width);
      float scaleHeight = ((float) h / height);
      matrix.postScale(scaleWidht, scaleHeight);
      newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
    }
    return newbmp;
  }

  /**
   * 图片圆角
   */
  public static Bitmap filletBitmap(Bitmap bitmap, int pixels) {
    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(output);
    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
    final RectF rectF = new RectF(rect);
    final float roundPx = pixels;
    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);
    return output;
  }

  /**
   * 旋转图片
   *
   * @return Bitmap
   */
  public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
    if (null == bitmap) {
      return null;
    }
    // 旋转图片 动作
    Matrix matrix = new Matrix();
    matrix.postRotate(angle);
    // 创建新的图片
    Bitmap resizedBitmap = Bitmap
        .createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    return resizedBitmap;
  }

  public static Bitmap LoadBitmap(String filePath) {
    return LoadBitmap(filePath, 0, 0, 0);
  }

  public static Bitmap LoadBitmap(String filePath, float width, float height, int BitmapSize) {
    // BitmapSize kb
    long maxSize = Runtime.getRuntime().maxMemory() / 10 / 1024;
    final ActivityManager activityManager = (ActivityManager) App.getContext()
        .getSystemService(Context.ACTIVITY_SERVICE);
    ActivityManager.MemoryInfo info = new ActivityManager.MemoryInfo();
    activityManager.getMemoryInfo(info);
    Log.e("nextmomery", "系统剩余内存:" + (info.availMem >> 10) / 1024 + "M");
    Log.e("lowmemory--", "系统是否处于低内存运行：" + info.lowMemory);
    Log.e("lowmemory _or_no", "当系统剩余内存低于" + info.threshold / 1024 / 1024 + "M时就看成低内存运行");

    if (BitmapSize > maxSize && maxSize > 100) {
      BitmapSize = (int) maxSize;
    }
    if (BitmapSize == 0) {
      BitmapSize = 400;
    }
    try {
      Options options = new Options();
      options.inJustDecodeBounds = true;
      Bitmap bmap = BitmapFactory.decodeFile(filePath, options);
      options.inJustDecodeBounds = false;
      int bitmapWidth = options.outWidth;
      int bitmapHeight = options.outHeight;
      float reqWidth = 0;
      float reqHeight = 0;
      if (0 == width || 0 == height) {
        reqWidth = 480f;
        reqHeight = 800f;
      } else {
        if (width >= bitmapWidth && height >= bitmapHeight) {
          bmap = BitmapFactory.decodeFile(filePath, options);
          return bmap;
        }
        reqWidth = width;
        reqHeight = height;
      }
      int b = 1;
      if (bitmapWidth > reqWidth && bitmapWidth > bitmapHeight) {
        b = (int) (options.outWidth / reqWidth);
      } else if (bitmapHeight > bitmapWidth && bitmapHeight > reqHeight) {
        b = (int) (options.outHeight / reqHeight);
      }
      if (b <= 0) {
        b = 1;
      }
      options.inSampleSize = b;
      // options.inPreferredConfig = Config.ARGB_4444;
      bmap = BitmapFactory.decodeFile(filePath, options);
      ByteArrayOutputStream bout = new ByteArrayOutputStream();
      bmap.compress(CompressFormat.JPEG, 100, bout);
      int opt = 100;
      while (bout.toByteArray().length / 1024 > BitmapSize) {
        bout.reset();
        bmap.compress(CompressFormat.JPEG, opt, bout);
        opt -= 10;
        if (opt == 10) {
          break;
        }
      }
      ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
      Bitmap bitmap = BitmapFactory.decodeStream(bin, null, null);
      return bitmap;
    } catch (Exception e) {
      // TODO: handle exception
      return null;
    }

  }

  public static Bitmap getCircleBitmap(Uri uri) {
    Bitmap src = BitmapFactory.decodeFile(uri.getPath());
    Bitmap output = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Config.RGB_565);
    Canvas canvas = new Canvas(output);
    Paint paint = new Paint();
    Rect rect = new Rect(0, 0, src.getWidth(), src.getHeight());
    paint.setAntiAlias(true);
    paint.setFilterBitmap(true);
    paint.setDither(true);
    canvas.drawARGB(0, 0, 0, 0);
    canvas.drawCircle(src.getWidth() / 2, src.getWidth() / 2, src.getWidth() / 2, paint);
    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
    canvas.drawBitmap(src, rect, rect, paint);
    getBitmapsize(output);
    return output;
  }

  @SuppressLint("NewApi")
  public static long getBitmapsize(Bitmap bitmap) {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
      return bitmap.getByteCount();
    }
    // Pre HC-MR1
    return bitmap.getRowBytes() * bitmap.getHeight();

  }

  public static void LoadBitmap(final IBmapWorker callBack) {

    final Handler handler = new Handler() {

      @Override
      public void handleMessage(Message msg) {

        Bundle bundle = msg.getData();
        String runState = bundle.getString("runstate");
        if ("success".equals(runState)) {
          Parcelable parcelble = bundle.getParcelable("data");
          callBack.UpDataUI(parcelble);
        } else if ("error".equals(runState)) {
          Serializable ser = bundle.getSerializable("data");
          ((Throwable) ser).printStackTrace();
          callBack.UpDataUI(null);
        } else {
          callBack.UpDataUI(null);
        }

      }

    };

    new Thread(new Runnable() {

      @Override
      public void run() {
        Message msg = new Message();
        Bundle bundle = new Bundle();
        try {
          bundle.putString("runstate", "success");
          bundle.putParcelable("data", callBack.Decode());
        } catch (Exception e) {
          bundle.putString("runstate", "error");
          bundle.putSerializable("data", e);
        }
        msg.setData(bundle);
        handler.sendMessage(msg);
      }
    }).start();

  }

  public Bitmap getBitmap(String Path) {
    Options options = new Options();
    options.inJustDecodeBounds = true;
    Bitmap bmap = BitmapFactory.decodeFile(Path, options);
    options.inJustDecodeBounds = false;
    int width = options.outWidth;
    int height = options.outHeight;
    float rh = 800f;
    float rw = 480f;
    int b = 1;
    if (width > height && width > rw) {
      b = (int) (options.outWidth / rw);
    } else if (width < height && height > rh) {
      b = (int) (options.outHeight / rh);
    }
    if (b <= 0) {
      b = 1;
    }
    options.inSampleSize = b;
    bmap = BitmapFactory.decodeFile(Path, options);
    ByteArrayOutputStream baout = new ByteArrayOutputStream();
    bmap.compress(CompressFormat.JPEG, 100, baout);
    int ops = 100;
    while (baout.toByteArray().length / 1024 > 400) {
      baout.reset();
      ops -= 10;
      bmap.compress(CompressFormat.JPEG, ops, baout);
      if (ops == 0) {
        break;
      }

    }
    ByteArrayInputStream bain = new ByteArrayInputStream(baout.toByteArray());
    Bitmap bitmap = BitmapFactory.decodeStream(bain, null, null);
    return bitmap;
  }

  @SuppressLint("SimpleDateFormat")
  public static String compressBitmap(String path, float width, float height, int BitmapSize) {
    String dir = "";
    File file;
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
        || !Environment.isExternalStorageRemovable()) {
      dir = App.getContext().getExternalCacheDir().getPath();
    } else {
      dir = App.getContext().getCacheDir().getPath();
    }
    file = new File(dir + File.separator + "temppic");
    if (!file.exists()) {
      file.mkdirs();
    }
    try {
      String fileName = new SimpleDateFormat("yyyyMMdd_HHmmss_")
          .format(new Date(System.currentTimeMillis()));
      File pic = new File(file, fileName + ".jpg");
      long maxSize = Runtime.getRuntime().maxMemory() / 10 / 1024;
      if (BitmapSize > maxSize && maxSize > 400) {
        BitmapSize = (int) maxSize;
      }
      if (BitmapSize == 0) {
        BitmapSize = 400;
      }
      Options options = new Options();
      options.inJustDecodeBounds = true;//设置不将图片读到内存中，依然可以计算图片大小
      Bitmap bmap = BitmapFactory.decodeFile(path, options);
      options.inJustDecodeBounds = false;
      int bitmapWidth = options.outWidth;
      int bitmapHeight = options.outHeight;
      float reqWidth = 0;
      float reqHeight = 0;
      if (0 == width || 0 == height) {
        reqWidth = 480f;//针对一般手机的800*480分辨率进行压缩
        reqHeight = 800f;
      } else {
        reqWidth = width;
        reqHeight = height;
      }
      int b = 1;//设置缩放值 1为宽度和高度不进行缩放
      if (bitmapWidth > reqWidth && bitmapWidth > bitmapHeight) {
        b = (int) (options.outWidth / reqWidth);
      } else if (bitmapHeight > bitmapWidth && bitmapHeight > reqHeight) {
        b = (int) (options.outHeight / reqHeight);
      }
      if (b <= 0) {
        b = 1;
      }
      options.inSampleSize = b;
      bmap = BitmapFactory.decodeFile(path, options);
      ByteArrayOutputStream bout = new ByteArrayOutputStream();
      bmap.compress(CompressFormat.JPEG, 100, bout);
      int opt = 100;
      while (bout.toByteArray().length / 1024 > BitmapSize) {
        bout.reset();
        bmap.compress(CompressFormat.JPEG, opt, bout);
        opt -= 10;
        if (opt == 10) {
          break;
        }
      }
      ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
      Bitmap bitmap = BitmapFactory.decodeStream(bin, null, null);
      if (null != bitmap) {
        FileOutputStream fout = new FileOutputStream(pic);
        bitmap.compress(CompressFormat.JPEG, 100, fout);
        String picPath = pic.getAbsolutePath();
        return picPath;
      }
    } catch (Exception e) {
      // TODO: handle exception
      Log.e("error---", e.toString());
    }
    return "";
  }


  @SuppressLint("SimpleDateFormat")
  public static String compressBitmapsmallfile(String path, float width, float height,
      int BitmapSize) {//质量压缩为30%,用于不重要图片压缩
    String dir = "";
    File file;
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
        || !Environment.isExternalStorageRemovable()) {
      dir = App.getContext().getExternalCacheDir().getPath();
    } else {
      dir = App.getContext().getCacheDir().getPath();
    }
    file = new File(dir + File.separator + "temppic");
    if (!file.exists()) {
      file.mkdirs();
    }
    try {
      String fileName = new SimpleDateFormat("yyyyMMdd_HHmmss_")
          .format(new Date(System.currentTimeMillis()));
      File pic = new File(file, fileName + ".jpg");
      long maxSize = Runtime.getRuntime().maxMemory() / 10 / 1024;
      if (BitmapSize > maxSize && maxSize > 400) {
        BitmapSize = (int) maxSize;
      }
      if (BitmapSize == 0) {
        BitmapSize = 400;
      }
      Options options = new Options();
      options.inJustDecodeBounds = true;//设置不将图片读到内存中，依然可以计算图片大小
      Bitmap bmap = BitmapFactory.decodeFile(path, options);
      options.inJustDecodeBounds = false;
      int bitmapWidth = options.outWidth;
      int bitmapHeight = options.outHeight;
      float reqWidth = 0;
      float reqHeight = 0;
      if (0 == width || 0 == height) {
        reqWidth = 480f;//针对一般手机的800*480分辨率进行压缩
        reqHeight = 800f;
      } else {
        reqWidth = width;
        reqHeight = height;
      }
      int b = 1;//设置缩放值 1为宽度和高度不进行缩放
      if (bitmapWidth > reqWidth && bitmapWidth > bitmapHeight) {
        b = (int) (options.outWidth / reqWidth);
      } else if (bitmapHeight > bitmapWidth && bitmapHeight > reqHeight) {
        b = (int) (options.outHeight / reqHeight);
      }
      if (b <= 0) {
        b = 1;
      }
      options.inSampleSize = b;
      bmap = BitmapFactory.decodeFile(path, options);
      ByteArrayOutputStream bout = new ByteArrayOutputStream();
      bmap.compress(CompressFormat.JPEG, 30, bout);
      int opt = 100;
      while (bout.toByteArray().length / 1024 > BitmapSize) {
        bout.reset();
        bmap.compress(CompressFormat.JPEG, opt, bout);
        opt -= 10;
        if (opt == 10) {
          break;
        }
      }
      ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
      Bitmap bitmap = BitmapFactory.decodeStream(bin, null, null);
      if (null != bitmap) {
        FileOutputStream fout = new FileOutputStream(pic);
        bitmap.compress(CompressFormat.JPEG, 30, fout);
        String picPath = pic.getAbsolutePath();
        return picPath;
      }
    } catch (Exception e) {
      // TODO: handle exception
      Log.e("error---", e.toString());
    }
    return "";
  }

  public static Map<String, File> compressBitmap(Map<String, String> fcOrIdMap,
      List<String> showPaths, float w,
      float h, int BitmapSize) {
    Map<String, File> map = new HashMap<String, File>();
    List<String> list_show = null;
    File fcFile;
    File idFile;
    // File showFile;
    String fcPath = "";
    String IDPath = "";
    String dir = "";
    File file;
    FileOutputStream fout;
    long maxSize = Runtime.getRuntime().maxMemory() / 10 / 1024;
    if (BitmapSize > maxSize && maxSize > 100) {
      BitmapSize = (int) maxSize;
    }
    if (BitmapSize == 0) {
      BitmapSize = 400;
    }
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
        || !Environment.isExternalStorageRemovable()) {
      dir = App.getContext().getExternalCacheDir().getPath();
    } else {
      dir = App.getContext().getCacheDir().getPath();
    }
    file = new File(dir + File.separator + "temppic");
    if (!file.exists()) {
      file.mkdirs();
    }
    try {
      if (null != fcOrIdMap && !fcOrIdMap.isEmpty()) {
        if (fcOrIdMap.containsKey("fc")) {
          fcPath = fcOrIdMap.get("fc");
        }
        if (fcOrIdMap.containsKey("sf")) {
          IDPath = fcOrIdMap.get("sf");
        }
      }
      boolean suc = false;
      if (!Util.isNull(fcPath)) {
        Bitmap b = compressBitmapWH(fcPath, w, h, BitmapSize);
        if (null != b) {
          fcFile = new File(file, System.currentTimeMillis() + "_fc.jpg");
          try {
            fout = new FileOutputStream(fcFile);
            b.compress(CompressFormat.JPEG, 100, fout);
            suc = true;
          } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            suc = false;
          }
          if (suc) {
            map.put("fc", fcFile);
          }
          Log.e("fcFile_lenght--", (fcFile.length() / 1024) + "k");
        }
      }
      if (!Util.isNull(IDPath)) {
        Bitmap idBitmap = compressBitmapWH(IDPath, w, h, BitmapSize);
        if (null != idBitmap) {
          idFile = new File(file, System.currentTimeMillis() + "_idcard.jpg");
          try {
            fout = new FileOutputStream(idFile);
            idBitmap.compress(CompressFormat.JPEG, 100, fout);
            suc = true;
          } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            suc = false;
          }
          if (suc) {
            map.put("sf", idFile);
          }
          Log.e("idFile_lenght--", (idFile.length() / 1024) + "k");
        }
      }
      if (null != showPaths && showPaths.size() > 0) {
        list_show = compressBitmap(showPaths, w, h, BitmapSize);
        if (null != list_show && list_show.size() > 0) {
          for (int i = 0; i < list_show.size(); i++) {
            map.put("file" + i, new File(list_show.get(i)));
            Log.e("file--" + i, (new File(list_show.get(i)).length() / 1024) + "k");
          }
        }
      }
      if (null != map && !map.isEmpty()) {
        int size = 0;
        for (String key : map.keySet()) {
          size += map.get(key).length();
        }
        Log.e("all_pic_lenght--", size / 1024 + "k");
        if (size > 10 * 1024 * 1024) {
          if (null != list_show && list_show.size() > 0) {
            list_show = compressBitmap(list_show, w, h, BitmapSize);
            if (null != list_show && list_show.size() > 0) {
              for (int i = 0; i < list_show.size(); i++) {
                map.put("file" + i, new File(list_show.get(i)));
              }
            }
          }
        }
      }
      return map;
    } catch (Exception e) {
      return null;
    }
  }

  public static Bitmap compressBitmapQA(Bitmap b, int BitmapSize) {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    if (null != b) {
      try {
        b.compress(CompressFormat.JPEG, 100, bout);
        int opt = 100;
        while (bout.toByteArray().length / 1024 > BitmapSize) {
          bout.reset();
          b.compress(CompressFormat.JPEG, opt, bout);
          opt -= 10;
          if (opt == 10) {
            break;
          }
        }
        ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
        Bitmap bitmap = BitmapFactory.decodeStream(bin, null, null);
        if (null != bitmap) {
          return bitmap;
        }
      } catch (Exception e) {
        return null;
      }
    }
    return null;
  }

  public static Bitmap compressBitmapWH(String path, float width, float height, int BitmapSize) {
    try {
      long maxSize = Runtime.getRuntime().maxMemory() / 10 / 1024;

      if (BitmapSize > maxSize && maxSize > 100) {
        BitmapSize = (int) maxSize;
      }
      if (BitmapSize == 0) {
        BitmapSize = 400;
      }
      Options options = new Options();
      options.inJustDecodeBounds = true;
      Bitmap bmap = BitmapFactory.decodeFile(path, options);
      options.inJustDecodeBounds = false;
      int bitmapWidth = options.outWidth;
      int bitmapHeight = options.outHeight;
      float reqWidth = 0;
      float reqHeight = 0;
      if (0 == width || 0 == height) {
        reqWidth = 480f;
        reqHeight = 800f;
      } else {
        reqWidth = width;
        reqHeight = height;
      }
      int b = 1;
      if (bitmapWidth > reqWidth && bitmapWidth > bitmapHeight) {
        b = (int) (options.outWidth / reqWidth);
      } else if (bitmapHeight > bitmapWidth && bitmapHeight > reqHeight) {
        b = (int) (options.outHeight / reqHeight);
      }
      if (b <= 0) {
        b = 1;
      }
      options.inSampleSize = b;
      bmap = BitmapFactory.decodeFile(path, options);
      ByteArrayOutputStream bout = new ByteArrayOutputStream();
      bmap.compress(CompressFormat.JPEG, 100, bout);
      return compressBitmapQA(bmap, BitmapSize);
    } catch (Exception e) {
      return null;
    }
  }

  public static Bitmap compressBitmapWH(Bitmap bitmap, float width, float height, int BitmapSize) {

    if (null == bitmap) {
      return null;
    }
    int bitmapWidth = bitmap.getWidth();
    int bitmapHeight = bitmap.getHeight();
    try {
      long maxSize = Runtime.getRuntime().maxMemory() / 10 / 1024;

      if (BitmapSize > maxSize && maxSize > 100) {
        BitmapSize = (int) maxSize;
      }
      if (BitmapSize == 0) {
        BitmapSize = 400;
      }
      float reqWidth = 0;
      float reqHeight = 0;
      if (0 == width || 0 == height) {
        return compressBitmapQA(bitmap, BitmapSize);
      } else {
        reqWidth = width;
        reqHeight = height;
      }
      float scaleWidth = ((float) reqWidth) / width;
      float scaleHeight = ((float) reqHeight) / height;
      if (scaleWidth == 0) {
        scaleWidth = 1;
      }
      if (scaleHeight == 0) {
        scaleHeight = 1;
      }
      Matrix matrix = new Matrix();
      matrix.postScale(scaleWidth, scaleWidth);
      Bitmap b = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, true);
      if (null != b) {
        return compressBitmapQA(b, BitmapSize);
      } else {
        return compressBitmapQA(bitmap, BitmapSize);
      }
    } catch (Exception e) {
      return null;
    }
  }

  @SuppressLint("SimpleDateFormat")
  public static List<String> compressBitmap(List<String> paths, float width, float height,
      int BitmapSize) {
    List<String> list = new ArrayList<String>();
    if (null != paths && paths.size() > 0) {
      String dir = "";
      File file;
      if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
          || !Environment.isExternalStorageRemovable()) {
        dir = App.getContext().getExternalCacheDir().getPath();
      } else {
        dir = App.getContext().getCacheDir().getPath();
      }
      file = new File(dir + File.separator + "temppic");
      if (!file.exists()) {
        file.mkdirs();
      }
      try {
        for (int i = 0; i < paths.size(); i++) {
          String path = paths.get(i);
          String fileName = new SimpleDateFormat("yyyyMMdd_HHmmss_" + i)
              .format(new Date(System.currentTimeMillis()));
          File pic = new File(file, fileName + ".jpg");
          long maxSize = Runtime.getRuntime().maxMemory() / 10 / 1024;
          final ActivityManager activityManager = (ActivityManager) App.getContext()
              .getSystemService(Context.ACTIVITY_SERVICE);
          ActivityManager.MemoryInfo info = new ActivityManager.MemoryInfo();
          activityManager.getMemoryInfo(info);
          // Log.e("nextmomery", "系统剩余内存:" + (info.availMem >> 10) /
          // 1024 + "M");
          // Log.e("lowmemory--", "系统是否处于低内存运行：" + info.lowMemory);
          // Log.e("lowmemory _or_no", "当系统剩余内存低于" + info.threshold /
          // 1024 / 1024 + "M时就看成低内存运行");

          if (BitmapSize > maxSize && maxSize > 100) {
            BitmapSize = (int) maxSize;
          }
          if (BitmapSize == 0) {
            BitmapSize = 400;
          }
          Options options = new Options();
          options.inJustDecodeBounds = true;
          Bitmap bmap = BitmapFactory.decodeFile(path, options);
          options.inJustDecodeBounds = false;
          int bitmapWidth = options.outWidth;
          int bitmapHeight = options.outHeight;
          float reqWidth = 0;
          float reqHeight = 0;
          if (0 == width || 0 == height) {
            reqWidth = 480f;
            reqHeight = 800f;
          } else {
            reqWidth = width;
            reqHeight = height;
          }
          int b = 1;
          if (bitmapWidth > reqWidth && bitmapWidth > bitmapHeight) {
            b = (int) (options.outWidth / reqWidth);
          } else if (bitmapHeight > bitmapWidth && bitmapHeight > reqHeight) {
            b = (int) (options.outHeight / reqHeight);
          }
          if (b <= 0) {
            b = 1;
          }
          options.inSampleSize = b;
          bmap = BitmapFactory.decodeFile(path, options);
          ByteArrayOutputStream bout = new ByteArrayOutputStream();
          bmap.compress(CompressFormat.JPEG, 100, bout);
          int opt = 100;
          while (bout.toByteArray().length / 1024 > BitmapSize) {
            bout.reset();
            bmap.compress(CompressFormat.JPEG, opt, bout);
            opt -= 10;
            if (opt == 10) {
              break;
            }
          }
          ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
          Bitmap bitmap = BitmapFactory.decodeStream(bin, null, null);
          if (null != bitmap) {
            FileOutputStream fout = new FileOutputStream(pic);
            bitmap.compress(CompressFormat.JPEG, 100, fout);
            list.add(pic.getAbsolutePath());
          }
        }
      } catch (Exception e) {
        // TODO: handle exception
        Log.e("error---", e.toString());
      }
    }
    if (list.size() > 0) {
      return list;
    }
    return null;
  }

  public static String compressBitmapWH(String picPath, int w, int h) {
    File pic;
    if (!Util.isNull(picPath)) {
      try {
        pic = FileUtils.createTmpFile(App.getContext());
        if (0 == w || h == 0) {
          w = 480;
          h = 800;
        }
        Options options = new Options();
        options.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(picPath, options);
        options.inJustDecodeBounds = false;
        int bw = options.outWidth;
        int bh = options.outHeight;
        int b = 1;
        if (w < bw && bw > bh) {
          b = (int) options.outWidth / w;
        } else if (h < bh && bh < bw) {
          b = (int) options.outHeight / h;
        }
        if (b <= 0) {
          b = 1;
        }
        options.inSampleSize = b;
        bitmap = BitmapFactory.decodeFile(picPath, options);
        FileOutputStream fout = new FileOutputStream(pic);
        bitmap.compress(CompressFormat.JPEG, 100, fout);
        return pic.getAbsolutePath();
      } catch (IOException e) {
        e.printStackTrace();
        Log.e("e--", e.toString());
      }
    }
    return "";
  }

  public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(output);
    final int color = 0xff424242;
    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
    final RectF rectF = new RectF(rect);
    final float roundPx = pixels;
    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);
    canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);
    return output;
  }

  public static Bitmap LoadBitmap(String uri, int width, int height, int size) {
    Bitmap bitmap = null;
    if (!Util.isNull(uri)) {
      try {
        URL url = new URL(uri);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(45000);
        conn.setRequestMethod("GET");
        InputStream in = conn.getInputStream();
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
          bitmap = BitmapFactory.decodeStream(in);
          if (null != bitmap) {
            if (width != 0 && height != 0) {
              bitmap = compressBitmapWH(bitmap, width, height, size);
            } else if (size != 0) {
              bitmap = compressBitmapQA(bitmap, size);
            }
          }
          return bitmap;
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return null;
  }

  public static Bitmap makeRoundCorner(Bitmap bitmap) {
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    int left = 0, top = 0, right = width, bottom = height;
    float roundPx = height / 2;
    if (width > height) {
      left = (width - height) / 2;
      top = 0;
      right = left + height;
      bottom = height;
    } else if (height > width) {
      left = 0;
      top = (height - width) / 2;
      right = width;
      bottom = top + width;
      roundPx = width / 2;
    }
    Log.e("TAG:", "ps:" + left + ", " + top + ", " + right + ", " + bottom);

    Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
    Canvas canvas = new Canvas(output);
    int color = 0xff424242;
    Paint paint = new Paint();
    Rect rect = new Rect(left, top, right, bottom);
    RectF rectF = new RectF(rect);

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);
    canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);
    return output;
  }

  /**
   * @param bitmap 原图
   * @param edgeLength 希望得到的正方形部分的边长
   * @return 缩放截取正中部分后的位图。
   */
  public static Bitmap centerSquareScaleBitmap(Bitmap bitmap, int edgeLength) {
    if (null == bitmap || edgeLength <= 0) {
      return null;
    }

    Bitmap result = bitmap;
    int widthOrg = bitmap.getWidth();
    int heightOrg = bitmap.getHeight();

    if (widthOrg > edgeLength && heightOrg > edgeLength) {
      //压缩到一个最小长度是edgeLength的bitmap
      int longerEdge = (int) (edgeLength * Math.max(widthOrg, heightOrg) / Math
          .min(widthOrg, heightOrg));
      int scaledWidth = widthOrg > heightOrg ? longerEdge : edgeLength;
      int scaledHeight = widthOrg > heightOrg ? edgeLength : longerEdge;
      Bitmap scaledBitmap;

      try {
        scaledBitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, true);
      } catch (Exception e) {
        return null;
      }

      //从图中截取正中间的正方形部分。
      int xTopLeft = (scaledWidth - edgeLength) / 2;
      int yTopLeft = (scaledHeight - edgeLength) / 2;

      try {
        result = Bitmap.createBitmap(scaledBitmap, xTopLeft, yTopLeft, edgeLength, edgeLength);
        scaledBitmap.recycle();
      } catch (Exception e) {
        return null;
      }
    }

    return result;
  }

  /**
   * 通过Base32将Bitmap转换成Base64字符串
   */
  public static String Bitmap2StrByBase64(Bitmap bit) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bit.compress(CompressFormat.JPEG, 40, bos);//参数100表示不压缩
    byte[] bytes = bos.toByteArray();
//        return (new sun.misc.BASE64Decoder()).encode(bytes);
    return Base64.encodeToString(bytes, Base64.NO_WRAP);
//        return com.alipay.sdk.pay.demo.Base64.encode(bytes);
  }

//    public static String getLogoPath() {
//        boolean suc = false;
//        FileOutputStream fout;
//        File file = null;
//        try {
////            File dir = FileUtils.createTmpFile(App.getContext());
////            String path = App.getContext().getCacheDir().getPath();
//            // 创建文件
//            file = FileUtils.getDiskCacheDir(App.getContext(),
//                    "cbLogo.png");
//            if (file.exists()) {
//                file.delete();
//            }
//
//            InputStream is = App.getContext().getResources().
//                    openRawResource(R.raw.logo);
//            Bitmap b = BitmapFactory.decodeStream(is);
//
////            Bitmap b = BitmapFactory.decodeResource(App.getContext().getResources(),
////                    R.mipmap.logo);
//            Paint mPaint = new Paint();
//            Canvas canvas = new Canvas();
//            canvas.drawBitmap(b, 80, 80, mPaint);
//            fout = new FileOutputStream(file);
//            b.compress(CompressFormat.PNG, 60, fout);
//            suc = true;
//        } catch (Exception e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//            Log.e("error--", e.toString());
//            suc = false;
//        }
//
//        if (suc) {
//            if (null != file) {
//                String imagePath = file.getPath();
//                Log.e("imagePath--", imagePath + "");
//                return imagePath;
//            }
//        }
//        return "";
//    }

}
